//------------------------------------------------------------------------------
// Copyright (c) 2008 www.dnaide.com
// Licensed under the MIT (MIT-LICENSE.txt)
//------------------------------------------------------------------------------
using System;
using System.Text;
using System.Globalization;
using System.Security.Cryptography;

namespace DNAide.Core
{
	public static partial class StringAide
	{

		/// <summary>
		/// Returns a copy of the string encrypted to a specified Hash algorithm
		/// </summary>
		/// <param name="value">Value</param>
		/// <param name="hashAlgorithm">HashAlgorithm</param>
		/// <returns></returns>
		public static String ToHash(String value, HashAlgorithmType hashAlgorithm)
		{
			string retval = string.Empty;
			if (!string.IsNullOrEmpty(value))
			{
				byte[] data;
				data = Encoding.Default.GetBytes(value);
				switch (hashAlgorithm)
				{
					case HashAlgorithmType.MD5:
						#region md5
						MD5 md5 = new MD5CryptoServiceProvider();
						md5.TransformFinalBlock(data, 0, data.Length);
						foreach (byte b in md5.Hash)
							retval += Convert.ToString(b, 16).ToUpper(CultureInfo.InvariantCulture).PadLeft(2, '0');
						md5.Clear();
						#endregion
						break;
					case HashAlgorithmType.SHA1:
						#region sha160
						SHA1 sha1 = new SHA1Managed();
						sha1.TransformFinalBlock(data, 0, data.Length);
						foreach (byte b in sha1.Hash)
							retval += Convert.ToString(b, 16).ToUpper(CultureInfo.InvariantCulture).PadLeft(2, '0');
						sha1.Clear();
						#endregion
						break;
					case HashAlgorithmType.SHA2:
						#region sha256
						SHA256 sha2 = new SHA256Managed();
						sha2.TransformFinalBlock(data, 0, data.Length);
						foreach (byte b in sha2.Hash)
							retval += Convert.ToString(b, 16).ToUpper(CultureInfo.InvariantCulture).PadLeft(2, '0');
						sha2.Clear();
						#endregion
						break;
					case HashAlgorithmType.SHA3:
						#region sha384
						SHA384 sha3 = new SHA384Managed();
						sha3.TransformFinalBlock(data, 0, data.Length);
						foreach (byte b in sha3.Hash)
							retval += Convert.ToString(b, 16).ToUpper(CultureInfo.InvariantCulture).PadLeft(2, '0');
						sha3.Clear();
						#endregion
						break;
					case HashAlgorithmType.SHA5:
						#region sha512
						SHA512 sha5 = new SHA512Managed();
						sha5.TransformFinalBlock(data, 0, data.Length);
						foreach (byte b in sha5.Hash)
							retval += Convert.ToString(b, 16).ToUpper(CultureInfo.InvariantCulture).PadLeft(2, '0');
						sha5.Clear();
						#endregion
						break;
				}
			}
			return retval;
		}

	}
}
